const {BookList} = require('../../models/BookList');

module.exports = async (req, res) => {
    var recoms = [];
    let opt = [
        {$match:{"listName":req.query.listName}},
        {
            $lookup:{
                from: "books",
                localField: "reBooks.ISBN",
                foreignField: "ISBN",
                as: "bookInfo"
            },
        },
        {
            $project:{
                "cover":1,
                "bookInfo.ISBN":1,
                "bookInfo.title":1,
                "bookInfo.author":1,
                "bookInfo.publisher":1,
                "bookInfo.img":1,
                "bookInfo.pubdate":1,
                "bookInfo.binding":1,
                "bookInfo.gist":1
            }
        },
    ];
    let opt2 = [
        {$unwind:"$reBooks"},
        
        {
            $lookup:{
                from: "commodities",
                localField: "reBooks.ISBN",
                foreignField: "ISBN",
                as: "books"
            },
        },
        {
            $project:{
                "books.ISBN":1,
                "books.customPrice":1,
            }
        },
        {$unwind:"$books"},
        {$group:{
           _id:{ISBN:"$books.ISBN"},
           minPrice:{$min:"$books.customPrice"}
          }
        }
    ]
    BookList.aggregate(opt, (err, data) => {
        var recoms = [];
        if (err) {
            res.status(500).send({errCode:"1",msg:"服务器内部错误"})
        } else {
            for(let i=0;i<data[0].bookInfo.length;i++){
                data[0].bookInfo[i].cover = data[0].cover;
                recoms.push(data[0].bookInfo[i])
            }
            for(let i=0;i<recoms.length;i++){
                let optArr = [].concat(opt2);
                optArr.splice(1,0,{$match:{"reBooks.ISBN":recoms[i].ISBN}})
                BookList.aggregate(optArr, (err,data)=>{
                    if(err){
                        res.status(500).send({errCode:"1",msg:"服务器内部错误"})
                    } else {
                        if(data.length !== 0){
                            for(let j=0; j < recoms.length;j++){
                              if(recoms[j].ISBN == data[0]._id.ISBN){
                               recoms[j].minPrice = data[0].minPrice
                              }
                            }
                        }
                        if(i == recoms.length-1){
                           res.send({errCode:"0",msg:"请求成功",data:{listContent:recoms}})
                        }  
                    }
                })
            }
            }
        }
    );
}